//
//  ReleaseBoJianVC.m
//  jinwang
//
//  Created by jzb on 2018/3/13.
//  Copyright © 2018年 jzb. All rights reserved.
//

#import "ReleaseBoJianVC.h"
#import <ZYQAssetPickerController.h>

#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MediaPlayer/MediaPlayer.h>
#import "AppDelegate.h"


#define appDelegate ((AppDelegate *)[UIApplication sharedApplication].delegate)

#define SCREEN_WITH     (float)(320)/(float)320*[[UIScreen mainScreen]bounds].size.width

#define SCREEN_HEIGHT     (float)(320)/(float)320*[[UIScreen mainScreen]bounds].size.height

#define TimeLineCellHighlightedColor [UIColor colorWithRed:92/255.0 green:140/255.0 blue:193/255.0 alpha:1.0]
#define SDColor(r, g, b, a) [UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:a]
#define TimeLineCellHighlightedColor [UIColor colorWithRed:92/255.0 green:140/255.0 blue:193/255.0 alpha:1.0]

@interface ReleaseBoJianVC ()<ZYQAssetPickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>
{
    //快照
    UIView               *_KuaiZhaoeditv;
    UIButton             *_KuaiZhaoaddPic;
    UIView               *_KuaiZhaoaddLineView;
    NSMutableArray       *_imageArray;
    NSArray *arr;
    NSMutableArray *_selectedPhotos;
    NSString *_KuaiZhaoPost_title;
    
    //爱拍
    UIView               *_AiPaieditv;
    UIButton             *_AiPaiaddPic;
    UIView               *_AiPaiaddLineView;
    NSURL                *_outputURL;
    NSString *_AiPaiPost_title;
    UIImage *_AaiPaiImg;//第一帧图片
    
    NSString *_storageRoot;//七牛地址
    
    //佳文
    UIImageView *_JiaWenImageView;
    NSString *_JiaWenPost_content;
    
}
@property (weak, nonatomic) IBOutlet UIButton *KuaizZhaoBtn;
@property (weak, nonatomic) IBOutlet UIButton *AiPaiBtn;
@property (weak, nonatomic) IBOutlet UIButton *JiaWengBtn;

@property (weak, nonatomic) IBOutlet UITextView *ContentTextView;
@property (weak, nonatomic) IBOutlet UILabel *PromptLabel;
@property (weak, nonatomic) IBOutlet UITextField *TitleTF;
@property (weak, nonatomic) IBOutlet UIView *TitleBGView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *TitleBGViewHeight;

@property (weak, nonatomic) IBOutlet UIView *ImageChoseBGView;

@property (weak, nonatomic) IBOutlet UIView *JiaWenBtnBGView;
@property (weak, nonatomic) IBOutlet UIView *JiaWenTextBGView;

@property (weak,nonatomic) NSString *post_type;//类型0快照1爱拍2佳文
@property (weak,nonatomic) NSString *post_content;//内容 快照爱拍的图片视频，佳文的内容，快照多个图片,号隔开

@property (nonatomic, strong)MBProgressHUD *hud;

@property (copy, nonatomic) NSString *videoQiNiuToken;

@property (nonatomic, copy)NSString *videoSuccessToken;

@property (nonatomic, copy)NSString *imageViewSuccessToken;


@property (strong, nonatomic) UITextView *serviceContentTextView;
@property (nonatomic,strong)NSMutableArray *imageUploadedArray;//图片数组
@property (nonatomic,strong)NSMutableArray *imageUploadedNameArray;//所有上传图片名字数组（上传图片之后，返回的名字）
@property (nonatomic,strong)NSMutableArray *imageDownloadedNameArray;//之前上传的oldHtmlString解析出来的图片地址

@property (nonatomic,strong)NSMutableArray *imageMarkArray;//图片对应的记号`0`表示第0张图片

@property (nonatomic,assign) BOOL hasEndDiv;
@property (nonatomic,assign) BOOL hasHeadDiv;
@property (nonatomic,assign) NSInteger imageIndex;
@property (nonatomic,strong) NSMutableString *resultString;//拼接之后的字符串

@property (nonatomic,strong)UIImagePickerController *pickerController;
@property (nonatomic,assign)CGFloat imageWidth;
@property (nonatomic,assign)CGFloat wordFont;

//光标位置
@property (nonatomic,assign)NSRange curserRange;

@end

@implementation ReleaseBoJianVC

- (void)dealloc {
    _imageUploadedArray = nil;
    _imageUploadedNameArray = nil;
    _imageDownloadedNameArray = nil;
    _imageMarkArray = nil;
    _pickerController = nil;
//    _returnBlock = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"发布";
    
    _post_type = @"0";
    
    //快照
    _imageArray = [NSMutableArray array];
    _KuaiZhaoeditv = [[UIView alloc] initWithFrame:CGRectMake(18, 200, SCREEN_WITH-18*2, 0)];
//    _editv.backgroundColor = [UIColor lightGrayColor];
    _KuaiZhaoaddPic = [UIButton buttonWithType:UIButtonTypeCustom];
    [_KuaiZhaoaddPic setImage:[UIImage imageNamed:@"jw_bojian_addImg"] forState:UIControlStateNormal];
    _KuaiZhaoaddPic.frame = CGRectMake(8, 10, (SCREEN_WITH - 18*4 - 30)/4, (SCREEN_WITH - 18*4 - 30)/4);
    [_KuaiZhaoaddPic addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    _KuaiZhaoeditv.frame = CGRectMake(18, 10, SCREEN_WITH-18*2, CGRectGetMaxY(_KuaiZhaoaddPic.frame)+10);
    [_KuaiZhaoeditv addSubview:_KuaiZhaoaddPic];
    
    _KuaiZhaoaddLineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_KuaiZhaoaddPic.frame)+10-1, SCREEN_WITH-18*2, 1)];
    _KuaiZhaoaddLineView.backgroundColor = UIColorHex(0xF0F0F0);
    [_KuaiZhaoeditv addSubview:_KuaiZhaoaddLineView];
    
    [_ImageChoseBGView addSubview:_KuaiZhaoeditv];
    
    //爱拍
    _AiPaieditv = [[UIView alloc] initWithFrame:CGRectMake(18, 200, SCREEN_WITH-18*2, 0)];
    //    _editv.backgroundColor = [UIColor lightGrayColor];
    
    _AiPaiaddPic = [UIButton buttonWithType:UIButtonTypeCustom];
    [_AiPaiaddPic setImage:[UIImage imageNamed:@"jw_bojian_addAiPai"] forState:UIControlStateNormal];
    _AiPaiaddPic.frame = CGRectMake(8, 10, 70, 70);
    [_AiPaiaddPic addTarget:self action:@selector(AiPaiclick:) forControlEvents:UIControlEventTouchUpInside];
    _AiPaieditv.frame = CGRectMake(18, 10, SCREEN_WITH-18*2, CGRectGetMaxY(_AiPaiaddPic.frame)+10);
    [_AiPaieditv addSubview:_AiPaiaddPic];
    
    _AiPaiaddLineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_AiPaiaddPic.frame)+10-1, SCREEN_WITH-18*2, 1)];
    _AiPaiaddLineView.backgroundColor = UIColorHex(0xF0F0F0);
    [_AiPaieditv addSubview:_AiPaiaddLineView];
    
    [_ImageChoseBGView addSubview:_AiPaieditv];
    _AiPaieditv.hidden = YES;
    
    [self getQiniuUploadToken];
    
    //佳文
    _JiaWenImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, _ImageChoseBGView.width-40, _ImageChoseBGView.height-80)];
    _JiaWenImageView.backgroundColor = [UIColor clearColor];
    _JiaWenImageView.hidden = YES;
    [_ImageChoseBGView addSubview:_JiaWenImageView];
    
    _wordFont = 16.0;
    _imageWidth = 300;
    
    _resultString = [[NSMutableString alloc] init];
    _imageUploadedArray = [[NSMutableArray alloc] init];
    _imageUploadedNameArray = [[NSMutableArray alloc] init];
    _imageDownloadedNameArray = [[NSMutableArray alloc] init];
    
    _imageMarkArray = [[NSMutableArray alloc] init];
    _serviceContentTextView = [[UITextView alloc]initWithFrame:CGRectMake(20, 10, kScreenWidth-40, _JiaWenTextBGView.height-70)];
    _serviceContentTextView.font = [UIFont systemFontOfSize:_wordFont];
    _serviceContentTextView.delegate = self;
    _serviceContentTextView.returnKeyType = UIReturnKeyDone;
    [_serviceContentTextView setFont:[UIFont systemFontOfSize:16]];
    [_JiaWenTextBGView addSubview:_serviceContentTextView];
//    if (_oldHtmlString != nil && ![_oldHtmlString isEqualToString:@""]) {
//        [self setOldStringToAttributeString:_oldHtmlString];
//    }
    
    if (_pickerController == nil) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            _pickerController = [[UIImagePickerController alloc] init];
            _pickerController.view.backgroundColor = [UIColor redColor];
            _pickerController.delegate = self;
            _pickerController.allowsEditing = NO;
        });
    }
    NSLog(@"光标位置%ld——%ld",_curserRange.location,_curserRange.length);
    
    if (_ExitType.length > 0) {
        _KuaizZhaoBtn.backgroundColor = UIColorHex(0xC8C8C8);
        _AiPaiBtn.backgroundColor = UIColorHex(0xC8C8C8);
        _JiaWengBtn.backgroundColor = UIColorHex(0xC8C8C8);
        [_KuaizZhaoBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_AiPaiBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_JiaWengBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _KuaizZhaoBtn.userInteractionEnabled=NO;
        _AiPaiBtn.userInteractionEnabled=NO;
        _JiaWengBtn.userInteractionEnabled=NO;
        if ([_ExitType isEqualToString:@"快照"]) {
            
            _KuaizZhaoBtn.backgroundColor = UIColorHex(0xEEA72B);
            [_KuaizZhaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
            _TitleBGViewHeight.constant = 0;
            _TitleBGView.hidden = YES;
            _post_type = @"0";
            _KuaiZhaoeditv.hidden = NO;
            _AiPaieditv.hidden = YES;
            _JiaWenBtnBGView.hidden = YES;
            _JiaWenImageView.hidden = YES;
            _JiaWenTextBGView.hidden = YES;
            
            _PromptLabel.hidden = YES;
            _ContentTextView.text = _model.post_title;
            NSArray* array = [_model.post_content componentsSeparatedByString:@","];
            _imageArray = [NSMutableArray arrayWithArray:array];
            [self nineGrid];
            
        }else if ([_ExitType isEqualToString:@"爱拍"]){
            
            _AiPaiBtn.backgroundColor = UIColorHex(0xEEA72B);
            [_AiPaiBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
            _TitleBGViewHeight.constant = 0;
            _TitleBGView.hidden = YES;
            _post_type = @"1";
            _KuaiZhaoeditv.hidden = YES;
            _AiPaieditv.hidden = NO;
            _JiaWenBtnBGView.hidden = YES;
            _JiaWenImageView.hidden = YES;
            _JiaWenTextBGView.hidden = YES;
            
            _PromptLabel.hidden = YES;
            _ContentTextView.text = _model.post_title;
            
            NSArray* array = [_model.post_content componentsSeparatedByString:@","];
            UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:array[0]]]];
            [_AiPaiaddPic setImage:img forState:UIControlStateNormal];
            
        }else if ([_ExitType isEqualToString:@"佳文"]){
            
            _JiaWengBtn.backgroundColor = UIColorHex(0xEEA72B);
            [_JiaWengBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
            _TitleBGViewHeight.constant = 60;
            _TitleBGView.hidden = NO;
            _post_type = @"2";
            _KuaiZhaoeditv.hidden = YES;
            _AiPaieditv.hidden = YES;
            _JiaWenBtnBGView.hidden = NO;
            _JiaWenImageView.hidden = NO;
            _JiaWenTextBGView.hidden = NO;
            
            _TitleTF.text = _model.post_title;
            
//            _serviceContentTextView.text = _model.post_content;
            NSArray *resultArray = [_model.post_content componentsSeparatedByString:@"<br>"];
            NSMutableAttributedString *resultAttributedString = [[NSMutableAttributedString alloc] init];
            for (int i = 0; i < resultArray.count; i ++) {
                NSLog(@"(%@)",resultArray[i]);
                if (![resultArray[i] isEqualToString:@""]) {
                    if ([(NSString *)resultArray[i] containsString:@"http"]) {
                        NSString *tempString = resultArray[i];
                        
                        NSLog(@"-=-=-=-=>>>%@",[self getURLFromStr:tempString]);
                        //                tempString = [tempString stringByReplacingOccurrencesOfString:appDelegate.webImageDir withString:@""];
                        [_imageDownloadedNameArray addObject:[self getURLFromStr:tempString]];
                        
                        NSTextAttachment *attch = [[NSTextAttachment alloc] init];
                        // 表情图片
                        attch.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[self getURLFromStr:tempString]]]];
                        //resultArray[i]
                        // 设置图片大小
                        attch.bounds = CGRectMake(0, 0, kScreenWidth-60, kScreenWidth-60);
                        
                        // 创建带有图片的富文本
                        NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
                        [resultAttributedString appendAttributedString:string];
                    } else {
                        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:resultArray[i]];
                        [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:_wordFont] range:NSMakeRange(0, [string length])];
                        [resultAttributedString appendAttributedString:string];
                    }
                }
            }
            _serviceContentTextView.attributedText = resultAttributedString;
            [_serviceContentTextView setFont:[UIFont systemFontOfSize:_wordFont]];
            
        }
    }
    
    
}
- (NSString*)getURLFromStr:(NSString *)string {
    NSError *error;
    //可以识别url的正则表达式
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    NSArray *arrayOfAllMatches = [regex matchesInString:string
                                                options:0
                                                  range:NSMakeRange(0, [string length])];
    
    //NSString *subStr;
//    NSMutableArray *arr=[[NSMutableArray alloc] init];
//
    NSString* substringForMatch;
    for (NSTextCheckingResult *match in arrayOfAllMatches){
        substringForMatch = [string substringWithRange:match.range];
//        [arr addObject:substringForMatch];
    }
    return substringForMatch;
}
- (IBAction)TypeChoseBtnOnclick:(UIButton *)sender {
    
    _KuaizZhaoBtn.backgroundColor = UIColorHex(0xC8C8C8);
    _AiPaiBtn.backgroundColor = UIColorHex(0xC8C8C8);
    _JiaWengBtn.backgroundColor = UIColorHex(0xC8C8C8);
    [_KuaizZhaoBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_AiPaiBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_JiaWengBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    sender.backgroundColor = UIColorHex(0xEEA72B);
    [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    if (sender.tag == 1000) {
        _TitleBGViewHeight.constant = 0;
        _TitleBGView.hidden = YES;
        _post_type = @"0";
        _KuaiZhaoeditv.hidden = NO;
        _AiPaieditv.hidden = YES;
        _JiaWenBtnBGView.hidden = YES;
        _JiaWenImageView.hidden = YES;
        _JiaWenTextBGView.hidden = YES;
        _ContentTextView.text = _KuaiZhaoPost_title;
        
    }else if (sender.tag == 1001){
        _TitleBGViewHeight.constant = 0;
        _TitleBGView.hidden = YES;
        _post_type = @"1";
        _KuaiZhaoeditv.hidden = YES;
        _AiPaieditv.hidden = NO;
        _JiaWenBtnBGView.hidden = YES;
        _JiaWenImageView.hidden = YES;
        _JiaWenTextBGView.hidden = YES;
        _ContentTextView.text =_AiPaiPost_title;
    }else{
        _TitleBGViewHeight.constant = 60;
        _TitleBGView.hidden = NO;
        _post_type = @"2";
        _KuaiZhaoeditv.hidden = YES;
        _AiPaieditv.hidden = YES;
        _JiaWenBtnBGView.hidden = NO;
        _JiaWenImageView.hidden = NO;
        _JiaWenTextBGView.hidden = NO;
        _ContentTextView.text =_JiaWenPost_content;
        
      
    }
    if (_ContentTextView.text.length > 0) {
        _PromptLabel.hidden = YES;
    }else{
        _PromptLabel.hidden = NO;
    }
}
- (IBAction)ReleaseBtnOnclick:(UIButton *)sender {
    
    if ([_post_type isEqualToString:@"0"]) {
        if(kStringIsEmpty(_ContentTextView.text)){
            [self showBottomMessag:@"请输入内容"];
            return ;
        }
        
        [self KuaiZhao_uploadImages];
    }else if ([_post_type isEqualToString:@"1"]){
        if (kStringIsEmpty(self.videoQiNiuToken) && kStringIsEmpty(_storageRoot)) {
            
        }else{
            if(kStringIsEmpty(_ContentTextView.text)){
                [self showBottomMessag:@"请输入内容"];
                return ;
            }
           
            [self AiPai_uploadVideo];
        }
    }else{
        if(kStringIsEmpty(_TitleTF.text)){
            [self showBottomMessag:@"请输入标题"];
            return ;
        }
        _hasEndDiv = false;
        _hasHeadDiv = false;
        _imageIndex = 0;
        
        NSAttributedString * att = _serviceContentTextView.attributedText;
        NSMutableAttributedString * resultAtt = [[NSMutableAttributedString alloc]initWithAttributedString:att];
        //    __weak __block UITextView * copy_self = self; //枚举出所有的附件字符串
        [att enumerateAttributesInRange:NSMakeRange(0, att.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
            NSTextAttachment * textAtt = attrs[@"NSAttachment"];//从字典中取得那一个图片
            if (textAtt) {
                if (self.hasEndDiv == true) {
//                    [_resultString insertString:@"<div>" atIndex:0];
                    self.hasHeadDiv = true;
                    self.hasEndDiv = false;
                }
                
                UIImage * image = textAtt.image;
                [_resultString insertString:[NSString stringWithFormat:@"`%ld`",self.imageIndex] atIndex:0];
                [self.imageMarkArray addObject:[NSString stringWithFormat:@"`%ld`",self.imageIndex]];
                [self.imageUploadedArray addObject:image];
                self.imageIndex ++;
            } else {
                if (self.hasEndDiv == false) {
//                    [_resultString insertString:@"</div>" atIndex:0];
                    self.hasEndDiv = true;
                }
                [_resultString insertString:[resultAtt attributedSubstringFromRange:range].string atIndex:0];
            }
        }];
        if (_hasEndDiv == true) {
//            [_resultString insertString:@"<div>" atIndex:0];
        }
        NSLog(@"%@",_resultString);
        //上传图片，拼接字符串
        if (self.imageUploadedArray.count > 0) {
            [self uploadImageArray];
        }
    }
}
- (void)uploadImageArray {
    _imageIndex = 0;//用来计数
    [MBProgressHUD showHUDAddedTo:self.view animated:true];
    for (int i = 0; i < _imageUploadedArray.count; i ++) {
        [self uploadHeadImage:_imageUploadedArray[i] imageIndex:i];
    }
}
- (void)uploadHeadImage:(UIImage *)image imageIndex:(NSInteger)index{
    
    //将图片上传到服务器
    [NSThread sleepForTimeInterval:0.5];
    [UploadImageTool uploadImage:image progress:^(NSString *key, float percent) {
        
    } success:^(NSString *url) {
        
        [_imageUploadedNameArray addObject:url];
        
        NSArray *array = [self.resultString componentsSeparatedByString:self.imageMarkArray[index]];

        if (array.count == 1) {
            if (index != 0) {//说明是最前面的一个image
                self.resultString = [NSMutableString stringWithFormat:@"<br><img src=\"%@\"><br>%@",url,array[0]];
            } else {//说明是最后面的一个image
                self.resultString = [NSMutableString stringWithFormat:@"%@<br><img src=\"%@\"><br>",array[0],url];
            }
        } else {
            self.resultString = [NSMutableString stringWithFormat:@"%@<br><img src=\"%@\"><br>%@",array[0],url,array[1]];
        }
        _imageIndex ++;
        if (_imageIndex == _imageUploadedArray.count) {//图片都上传完了
            
            if ([_ExitType isEqualToString:@"佳文"]) {
                
//                [self net_makeUrl_post_releaseWithpost_type:_post_type post_title:_TitleTF.text post_content:self.resultString];
                [self makeUrl_post_editPost_title:_TitleTF.text post_content:self.resultString];

            }else{
                
                [self net_makeUrl_post_releaseWithpost_type:_post_type post_title:_TitleTF.text post_content:self.resultString];

            }
            
            //删除在编辑中删掉的图片
            NSMutableArray *tempArray = [[NSMutableArray alloc] init];
            for (int i = 0; i < _imageDownloadedNameArray.count; i ++) {
                for (int j = 0; j < _imageUploadedNameArray.count; j ++) {
                    if ([_imageDownloadedNameArray[i] isEqualToString:_imageUploadedNameArray[j]]) {
                        continue;
                    }
                }
                [tempArray addObject:_imageDownloadedNameArray[i]];
            }
        }
        
    } failure:^{
        
    }];
}

- (IBAction)JiaWenAddImgBtnOnclick:(UIButton *)sender {
    
//    [self click];
    UIAlertController*ZhengC=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction*XiangCe=[UIAlertAction actionWithTitle:@"从手机相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:_pickerController animated:YES completion:nil];
    }];
    UIAlertAction*ZhaoXiang=[UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_pickerController animated:YES completion:nil];
        
    }];
    UIAlertAction*  Cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    
    [ZhengC addAction:XiangCe];
    [ZhengC addAction:ZhaoXiang];
    [ZhengC addAction:Cancel];
    [self presentViewController:ZhengC animated:YES completion:nil];
}

-(void)click{
    
    ZYQAssetPickerController *pickerController = [[ZYQAssetPickerController alloc] init];
    if ([_post_type isEqualToString:@"0"]) {
        pickerController.maximumNumberOfSelection = 9 - _imageArray.count;
    }else if ([_post_type isEqualToString:@"2"]){
        pickerController.maximumNumberOfSelection = 1;
    }
    
//    pickerController.nowCount = _imageArray.count;
    pickerController.assetsFilter = ZYQAssetsFilterAllPhotos;
    pickerController.showEmptyGroups=YES;
    pickerController.delegate=self;
    pickerController.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {

        if ([_post_type isEqualToString:@"0"] && pickerController.indexPathsForSelectedItems.count + _imageArray.count == 9) {
           [self showBottomMessag:@"最多选择9张图片"];
        }else if ([_post_type isEqualToString:@"2"] && pickerController.indexPathsForSelectedItems.count == 1){
            [self showBottomMessag:@"最多选择1张图片"];
        }
        if ([(ZYQAsset*)evaluatedObject mediaType]==ZYQAssetMediaTypeVideo) {
            NSTimeInterval duration = [(ZYQAsset*)evaluatedObject duration];
            
            return duration >= 5;
        } else {
            
            return YES;
        }
    }];
    [self presentViewController:pickerController animated:YES completion:nil];
}
- (void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                   {
                       for (int i=0; i<assets.count; i++)
                       {
                           ZYQAsset *asset = assets[i];
                           [asset setGetFullScreenImage:^(UIImage *result){
                               if (result == nil) {
                                   NSLog(@"空空以控控");
                               }
                               if(_imageArray.count >9){
                                   NSLog(@"超了");
                                   [self showBottomMessag:@"最多选择9张图片"];
                               }else{
                                   if ([_post_type isEqualToString:@"0"]) {
                                       [_imageArray addObject:result];
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           [self nineGrid];
                                       });
                                   }else if ([_post_type isEqualToString:@"2"]){
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           
                                           _JiaWenImageView.image = result;
                                       });
                                   }
                               }
                               NSLog(@"---%ld",_imageArray.count);
                           }];
                       }
                       NSLog(@"现在剩余是多少%ld",_imageArray.count);
                   });
}
-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}
// 删除照片
- (void)deleteEvent:(UIButton *)sender
{
    if (_imageArray.count == 9) {
        _KuaiZhaoaddPic.hidden = YES;
    }else{
        _KuaiZhaoaddPic.hidden = NO;
    }
    UIButton *btn = (UIButton *)sender;
    [_imageArray removeObjectAtIndex:btn.tag-10];
    
    [self nineGrid];
    
    if (_imageArray.count == 0)
    {
        _KuaiZhaoaddPic.frame = CGRectMake(8, 10, (SCREEN_WITH - 18*4 - 30)/4, (SCREEN_WITH - 18*4 - 30)/4);
        _KuaiZhaoeditv.frame = CGRectMake(18, 10, SCREEN_WITH-18*2, CGRectGetMaxY(_KuaiZhaoaddPic.frame)+10);
        _KuaiZhaoaddLineView.frame = CGRectMake(0, CGRectGetMaxY(_KuaiZhaoaddPic.frame)+10-1, SCREEN_WITH-18*2, 1);
    }
}
// 9宫格图片布局
- (void)nineGrid
{
    NSLog(@"九宫格%ld",_imageArray.count);
    if (_imageArray.count == 9) {
        _KuaiZhaoaddPic.hidden = YES;
    }else{
       _KuaiZhaoaddPic.hidden = NO;
    }
    for (UIImageView *imgv in _KuaiZhaoeditv.subviews)
    {
        if ([imgv isKindOfClass:[UIImageView class]]) {
            [imgv removeFromSuperview];
        }
    }
    
    CGFloat width = (SCREEN_WITH - 18*4 - 30)/4;
//    CGFloat widthSpace = (SCREEN_WITH - 18*4 - 70*4) / 3.0;
     CGFloat widthSpace = 10;
    CGFloat heightSpace = 10;
    
    NSInteger count = _imageArray.count;
    _imageArray.count > 9 ? (count = 9) : (count = _imageArray.count);
    
    for (int i=0; i<count; i++)
    {
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(18+(width+widthSpace)*(i%4), (i/4)*(width+heightSpace) + 10, width, width)];
        
        if ([_ExitType isEqualToString:@"快照"] && [_imageArray[i] isKindOfClass:[NSString class]]) {
            [imgv sd_setImageWithURL:[NSURL URLWithString:_imageArray[i]] placeholderImage:[UIImage imageNamed:@""]];
        }else{
            imgv.image = _imageArray[i];
        }
        imgv.userInteractionEnabled = YES;
        [_KuaiZhaoeditv addSubview:imgv];
        
        UIButton *delete = [UIButton buttonWithType:UIButtonTypeCustom];
        delete.frame = CGRectMake(width-12, -7, 16, 16);
        //        delete.backgroundColor = [UIColor greenColor];
        [delete setBackgroundImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        [delete addTarget:self action:@selector(deleteEvent:) forControlEvents:UIControlEventTouchUpInside];
        delete.tag = 10+i;
        [imgv addSubview:delete];
        
        if (i == _imageArray.count - 1)
        {
            if (_imageArray.count % 4 == 0) {
                _KuaiZhaoaddPic.frame = CGRectMake(8, CGRectGetMaxY(imgv.frame) + heightSpace, width, width);
            } else {
                _KuaiZhaoaddPic.frame = CGRectMake(CGRectGetMaxX(imgv.frame) + widthSpace, CGRectGetMinY(imgv.frame), width, width);
            }
            
            _KuaiZhaoeditv.frame = CGRectMake(18, 10, SCREEN_WITH-18*2, CGRectGetMaxY(_KuaiZhaoaddPic.frame)+10);
            _KuaiZhaoaddLineView.frame = CGRectMake(0, CGRectGetMaxY(_KuaiZhaoaddPic.frame)+10-1, SCREEN_WITH-18*2, 1);
        }
    }
}

-(UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);  //size 为CGSize类型，即你所需要的图片尺寸
    
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;   //返回的就是已经改变的图片
}
- (void)AiPaiclick:(UIButton *)sender{
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * firstAction = [UIAlertAction actionWithTitle:@"从相册获取视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self choosevideo];
    }];
    
    UIAlertAction * secondAction = [UIAlertAction actionWithTitle:@"录制视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self openLocalCamera];
    }];
    UIAlertAction * QuXiaoAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:firstAction];
    [alert addAction:secondAction];
    [alert addAction:QuXiaoAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)choosevideo
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    /**
     
     使用下面的会有下面俩个错误:
     1.[discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
     
     2.This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
     **/
    //    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    //    ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    
    ipc.mediaTypes = @[(NSString *)kUTTypeMovie];
    //最大录像时间
    //    ipc.videoMaximumDuration = 30.0f;//30秒
    ipc.delegate = self;//设置委托
    
    
    //    更改picker的导航条颜色 及item的tintcolor
    if ([ipc.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
        [ipc.navigationBar setBarTintColor:[UIColor grayColor]];
        [ipc.navigationBar setTranslucent:YES];
        [ipc.navigationBar setTintColor:[UIColor whiteColor]];
    }else{
        [ipc.navigationBar setBackgroundColor:[UIColor colorWithWhite:0.1 alpha:1.0]];
    }
    //    更改titieview的字体颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    
    attrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    [ipc.navigationBar setTitleTextAttributes:attrs];
    
    
    [self presentViewController:ipc animated:YES completion:nil];
    
}

- (void)openLocalCamera{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    //    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    //    ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    ipc.mediaTypes = @[(NSString *)kUTTypeMovie];//设置媒体类型为public.movie
    
    //最大录像时间
    //    ipc.videoMaximumDuration = 30.0f;//30秒
    ipc.delegate = self;//设置委托
    
    [self presentViewController:ipc animated:YES completion:nil];
    
}

//此方法可以获取文件的大小，返回的是单位是KB。
- (CGFloat) getFileSize:(NSString *)path
{
    NSLog(@"%@",path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}

//此方法可以获取视频文件的时长。
- (CGFloat) getVideoLength:(NSURL *)URL
{
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    if ([_post_type isEqualToString:@"2"]) {
        NSLog(@"选择了一张图片");
        UIImage *userImage = info[UIImagePickerControllerOriginalImage];
        userImage = [self scaleImage:userImage toScale:1];
        [_pickerController dismissViewControllerAnimated:YES completion:nil];
        
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithAttributedString:_serviceContentTextView.attributedText];
        NSTextAttachment *attch = [[NSTextAttachment alloc] init];
        // 表情图片
        attch.image = [self imageCompressForWidth:userImage targetWidth:kScreenWidth-60];
        // 设置图片大小
//        attch.bounds = CGRectMake(40, 0, kScreenWidth-60, kScreenWidth-60);
        
        // 创建带有图片的富文本
        NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
        [attri replaceCharactersInRange:_curserRange withAttributedString:string];
        
        // 用label的attributedText属性来使用富文本
        _serviceContentTextView.attributedText = attri;
        [_serviceContentTextView setFont:[UIFont systemFontOfSize:_wordFont]];
        
    }else{
        //获取视频url
        NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSURL *newVideoUrl ; //一般.mp4
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
        [formater setDateFormat:@"yyyyMMddHHmmss"];
        
        NSLog(@"时间戳: %@",[formater stringFromDate:[NSDate date]]);
        
        NSString *searchPatch = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *filePath = [searchPatch stringByAppendingPathComponent:@"/video/"];
        
        NSString *path = [filePath stringByAppendingFormat:@"%@.mp4",[formater stringFromDate:[NSDate date]]];
        newVideoUrl = [NSURL fileURLWithPath:path] ;//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
        
        //    newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/video/%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
        [self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
        
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
}
#pragma mark ------------图片处理------------------
//缩小图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize {
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
- (UIImage *)fixOrientation:(UIImage *)aImage {
        if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL
                               outputURL:(NSURL*)outputURL
                         completeHandler:(void (^)(AVAssetExportSession*))handler
{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
    //  NSLog(resultPath);
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.shouldOptimizeForNetworkUse= YES;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         switch (exportSession.status) {
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@"AVAssetExportSessionStatusCancelled");
                 break;
             case AVAssetExportSessionStatusUnknown:
                 NSLog(@"AVAssetExportSessionStatusUnknown");
                 
                 break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog(@"AVAssetExportSessionStatusWaiting");
                 
                 break;
             case AVAssetExportSessionStatusExporting:
                 NSLog(@"AVAssetExportSessionStatusExporting");
                 
                 break;
             case AVAssetExportSessionStatusCompleted:
                 NSLog(@"AVAssetExportSessionStatusCompleted");
                 _outputURL = outputURL;
//                 _AiPaiImageView.hidden = NO;
//                 _AiPaiImageView.image = [self getVideoPreViewImage];
                 
                 [self AiPaiaddPicChoseImg];
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@"AVAssetExportSessionStatusFailed");
                 
                 break;
         }
         
     }];
}
- (void)AiPaiaddPicChoseImg{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"打印当前的线程2: %@",[NSThread currentThread]);
        _AaiPaiImg = [self getVideoPreViewImage];
        [_AiPaiaddPic setImage:[self getVideoPreViewImage] forState:UIControlStateNormal];
    });
    
}
- (UIImage*) getVideoPreViewImage
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:_outputURL options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img = [[UIImage alloc] initWithCGImage:image];
    
    CGImageRelease(image);
    return img;
}


//图文混排
- (void)textViewDidChangeSelection:(UITextView *)textView {
    NSLog(@"光标位置%ld——%ld",textView.selectedRange.location,textView.selectedRange.length);
    _curserRange = textView.selectedRange;
}
- (void)setOldStringToAttributeString:(NSString *)oldHtmlString {
    NSString *oldString1 = oldHtmlString;
    oldString1 = [oldString1 stringByReplacingOccurrencesOfString:@"</div>" withString:@"<div>"];
    oldString1 = [oldString1 stringByReplacingOccurrencesOfString:@"<img src=\"" withString:@"<div>"];
    oldString1 = [oldString1 stringByReplacingOccurrencesOfString:@"\" style=\"width:99%\"/>" withString:@"<div>"];
    oldString1 = [oldString1 stringByReplacingOccurrencesOfString:@"<div><div>" withString:@"<div>"];
    NSArray *resultArray = [oldString1 componentsSeparatedByString:@"<div>"];
    NSMutableAttributedString *resultAttributedString = [[NSMutableAttributedString alloc] init];
    for (int i = 0; i < resultArray.count; i ++) {
        NSLog(@"(%@)",resultArray[i]);
        if (![resultArray[i] isEqualToString:@""]) {
            if ([(NSString *)resultArray[i] containsString:@"http"]) {
                NSString *tempString = resultArray[i];
//                tempString = [tempString stringByReplacingOccurrencesOfString:appDelegate.webImageDir withString:@""];
                [_imageDownloadedNameArray addObject:tempString];
                
                NSTextAttachment *attch = [[NSTextAttachment alloc] init];
                // 表情图片
                attch.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:resultArray[i]]]];
                // 设置图片大小
                attch.bounds = CGRectMake(0, 0, _imageWidth, _imageWidth);
                
                // 创建带有图片的富文本
                NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
                [resultAttributedString appendAttributedString:string];
            } else {
                NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:resultArray[i]];
                [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:_wordFont] range:NSMakeRange(0, [string length])];
                [resultAttributedString appendAttributedString:string];
            }
        }
    }
    _serviceContentTextView.attributedText = resultAttributedString;
    [_serviceContentTextView setFont:[UIFont systemFontOfSize:_wordFont]];
}
//快照上传到七牛
- (void)KuaiZhao_uploadImages{
    
    if (_imageArray.count > 0) {
        _selectedPhotos = [NSMutableArray new];

        for (int i=0; i<_imageArray.count; i++){
            if ([_imageArray[i] isKindOfClass:[UIImage class]]) {
                [_selectedPhotos addObject:_imageArray[i]];
                [_imageArray removeObjectAtIndex:i];
                i--;
            }
        }
        //将图片上传到服务器
        [NSThread sleepForTimeInterval:0.5];
        if (_selectedPhotos.count > 0) {
           
            [UploadImageTool uploadImages:_selectedPhotos progress:^(CGFloat totalProgress) {
                
            } success:^(NSArray *urlArr) {
                
                for (NSString *urlStr in urlArr) {
                    
                    [_imageArray addObject:urlStr];
                }
                
                _post_content = [_imageArray componentsJoinedByString:@","];
                if ([_ExitType isEqualToString:@"快照"]) {
                    [self makeUrl_post_editPost_title:_ContentTextView.text post_content:_post_content];
                }else{
                    [self net_makeUrl_post_releaseWithpost_type:_post_type post_title:_ContentTextView.text post_content:_post_content];
                }
                
            } failure:^{
                
            }];
            
        }else{
            _post_content = [_imageArray componentsJoinedByString:@","];
            if ([_ExitType isEqualToString:@"快照"]) {
                [self makeUrl_post_editPost_title:_ContentTextView.text post_content:_post_content];
            }
        }
        
    }else {
        [self showBottomMessag:@"请选择照片"];
    }
}
//爱拍上传视屏到七牛
- (void)AiPai_uploadVideo{
    
    CGImageRef cgref = [_AaiPaiImg CGImage];
    CIImage *cim = [_AaiPaiImg CIImage];
    if (cim == nil && cgref == NULL) {
        if ([_ExitType isEqualToString:@"爱拍"]) {
            
            [self makeUrl_post_editPost_title:_ContentTextView.text post_content:_model.post_content];
            return ;
        }else{
           
            [self showBottomMessag:@"请选择或录制视屏"];
            return ;
        }
    }
    static NSString *imgURL = @"";
    [UploadImageTool uploadImage:_AaiPaiImg progress:^(NSString *key, float percent) {
        
    } success:^(NSString *url) {
        //        [hud removeFromSuperview];
        
        NSLog(@"-=-=>>%@",url);
        imgURL = url;
    } failure:^{
        
    }];
    // 精确到毫秒
    NSString *millisecondTime =  [NSString stringWithFormat:@"%.f",[NSDate date].timeIntervalSince1970*1000];
    
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        NSData *data = [NSData dataWithContentsOfURL:_outputURL];
        
        QNUploadManager *managere =[[QNUploadManager alloc]init];
        
        QNUploadOption *option = [[QNUploadOption alloc]initWithMime:@"video/mp4" progressHandler:^(NSString *key, float percent) {
          
            NSLog(@"%f",percent);
        } params:nil checkCrc:NO cancellationSignal:nil];
        
        NSString *key = [NSString stringWithFormat:@"%@.mp4",millisecondTime];
        
        [managere putData:data key:key token:self.videoQiNiuToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            
            NSString *resp_key = resp[@"key"];
            if (resp_key.length > 0 && [resp_key isEqualToString:key]) {
                NSLog(@"video成功");
                
                self.videoSuccessToken = key;
                
                NSLog(@"0-0--=-=-=>>%@",self.videoSuccessToken);
                
                if ([_ExitType isEqualToString:@"爱拍"]) {
                    
                    [self makeUrl_post_editPost_title:_ContentTextView.text post_content:[NSString stringWithFormat:@"%@,%@%@",imgURL,_storageRoot,self.videoSuccessToken]];
                    return ;
                }else{
                  
                    [self net_makeUrl_post_releaseWithpost_type:_post_type post_title:_ContentTextView.text post_content:[NSString stringWithFormat:@"%@,%@%@",imgURL,_storageRoot,self.videoSuccessToken]];
                    
                }
                
                dispatch_group_leave(group);
                
            }else{
                NSLog(@"video失败");
                dispatch_group_leave(group);
                
            }
        } option:option];
    });
}
//佳文上传img到七牛
//- (void)JiaWen_uploadImage{
//
//    if (_JiaWenImageView.image) {
//        //将图片上传到服务器
////        __block MBProgressHUD *hud = [MBProgressHUD showActivityMessageInWindow:@"正在发布。。。"];
//        [NSThread sleepForTimeInterval:0.5];
//        [UploadImageTool uploadImage:_JiaWenImageView.image progress:^(NSString *key, float percent) {
//
//        } success:^(NSString *url) {
////            [hud removeFromSuperview];
//
//            NSLog(@"-=-=>>%@",url);
//            NSString *JiaWenContent = [NSString stringWithFormat:@"%@<br><img src=\"%@\" alt=\"152548684613549\"><br>",_ContentTextView.text,url];
//
//             [self net_makeUrl_post_releaseWithpost_type:_post_type post_title:_TitleTF.text post_content:[NSString stringWithFormat:@"%@",JiaWenContent]];
//        } failure:^{
//
//        }];
//
//    }else {
//        [self showBottomMessag:@"请选择照片"];
//
//    }
//
//}
#pragma mark -网络请求
//发布博见
-(void)net_makeUrl_post_releaseWithpost_type:(NSString *)post_type
                                  post_title:(NSString *)post_title
                                post_content:(NSString *)post_content{
    
    [[DDNetworkManagerDate makeUrl_post_releaseWithtoken:k_user_token post_type:post_type post_title:post_title post_content:post_content] post_RequestFinshSuccess:^(id responseObject) {
        
        NSLog(@"-=-=>>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            
            [self goBack];
        }
    } failure:^(id errorObject) {
        
        [self showBottomMessag:@"网络请求失败"];
    }];
}
//编辑博见
-(void)makeUrl_post_editPost_title:(NSString *)post_title
                      post_content:(NSString *)post_content{
    
    [[DDNetworkManagerDate makeUrl_post_editPostWithtoken:k_user_token post_id:[_model.post_id stringValue] post_title:post_title post_content:post_content] post_RequestFinshSuccess:^(id responseObject) {
        
        NSLog(@"-=-=>>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            
            [self goBack];
        }
    } failure:^(id errorObject) {
        
        [self showBottomMessag:@"网络请求失败"];
    }];
}


- (void)getQiniuUploadToken{
    //获取七牛上传信息 （/api/file/getQiniuUploadInfo)
    [[DDNetworkManagerDate makeUrl_getQiniuUploadInfo_token:k_user_token] post_RequestFinshSuccess:^(id responseObject) {
        int stateCode = [responseObject intValueForKey:kRequsetCode default:-1];
        if (stateCode == 1) {
            NSDictionary *dic = [responseObject objectForKey:kRequsetDataKey];
            
            self.videoQiNiuToken = dic[@"token"];
            _storageRoot = dic[@"url"];
            
            NSLog(@"-=-=>>><><>>%@",_storageRoot);

        }
    } failure:^(id errorObject) {
       
    }];
}

- (void)textViewDidChange:(UITextView *)textView{
    
    if (textView.text.length > 0) {
        _PromptLabel.hidden = YES;
    }else{
        _PromptLabel.hidden = NO;
    }
    
    if ([_post_type isEqualToString:@"0"]) {
        _KuaiZhaoPost_title = textView.text;
    }else if ([_post_type isEqualToString:@"1"]){
        _AiPaiPost_title = textView.text;
    }else if ([_post_type isEqualToString:@"2"]){
        _JiaWenPost_content = textView.text;
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
